package com.person.android.widgets.cutom_spinner;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.person.android.formatts.R;

import java.util.ArrayList;
import java.util.List;

/**
 * @autor zhaokang.
 * @time on 2015/12/13.
 */
public class SpinnerPopWindow extends PopupWindow implements AdapterView.OnItemClickListener {

    private Context mContext;
    private ListView mListView;
    private List<String> mFormatList = new ArrayList<>();
    private AbstractSpinnerAdapter mAdapter;
    private AbstractSpinnerAdapter.IOnItemSelectListener mItemSelectListener;

    public SpinnerPopWindow(Context context) {
        super(context);
        this.mContext = context;
        init();
    }

    private void init() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.spiner_window_layout, null);
        setContentView(view);
        setWidth(LayoutParams.WRAP_CONTENT);
        setHeight(LayoutParams.WRAP_CONTENT);
        setFocusable(true);
        /*ColorDrawable dw = new ColorDrawable(0x00);
        setBackgroundDrawable(dw);*/
        mListView = (ListView) view.findViewById(R.id.color_lv);
        mListView.setOnItemClickListener(this);
    }

    public void setItemListener(AbstractSpinnerAdapter.IOnItemSelectListener listener) {
        mItemSelectListener = listener;
    }

    public void setAdapter(AbstractSpinnerAdapter adapter) {
        mAdapter = adapter;
        mListView.setAdapter(mAdapter);
    }

    public void refreshData(List<String> list, int selIndex) {
        if (list != null && selIndex != -1) {
            this.mFormatList = list;
            if (mAdapter != null) {
                mAdapter.refreshData(list, selIndex);
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
        dismiss();
        if (mItemSelectListener != null) {
            mItemSelectListener.onItemClick(pos);
            if (mFormatList != null && mFormatList.size() > 0) {
                selectedFormat = mFormatList.get(pos);
            }
        }
    }

    private String selectedFormat;

    public String getSelectedItem() {
        return selectedFormat;
    }
}
